import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { refreshToken } from '@/api/user'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
  config => {
    const accessToken = store.getters.accessToken
    if (accessToken) {
      config.headers.Authorization = 'Bearer ' + accessToken
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code != 200) {
      return Promise.reject(res.message || 'Error')
    } else {
      return res
    }
  },
  error => {
    let errorMessage = '网络异常'
    if (error.response) {
      const errorResponse = error.response
      if (errorResponse.status == 401) {
        return handlerUnauthorized(error)
      } else if (errorResponse.status == 403) {
        errorMessage = '对不起,您没有操作权限,请联系管理员'
      } else if (errorResponse.status == 400) {
        errorMessage = handlerBadRequest(errorResponse)
      } else if (errorResponse.status == 500) {
        errorMessage = errorResponse.data.error.message;
      }
    }
    return Promise.reject(errorMessage)
  }
)

//处理请求接口返回400
function handlerBadRequest(errorResponse) {
  let validationErrors = errorResponse.data.validationErrors
  if (validationErrors) {
    const msgs = validationErrors.map(item => item.message);
    return msgs.join();
  } else {
    return errorResponse.data.message;
  }
}

//处理请求接口返回401
function handlerUnauthorized(error) {
  const reToken = store.getters.refreshToken
  if (reToken) {
    return refreshToken({ token: reToken }).then(response => {
      const { accessToken, refreshToken } = response
      store.dispatch('user/setToken', { accessToken, refreshToken })

      error.config.__isRetryRequest = true
      error.config.headers.Authorization = 'Bearer ' + accessToken
      return service(error.config)
    }).catch(() => {
      redirectLogin()
    })
  } else {
    redirectLogin()
  }
}

//重定向到登录
function redirectLogin() {
  store.dispatch('user/resetToken')
  router.replace({
    path: `/login`,
    query: { redirect: router.currentRoute.fullPath }
  })
}

export default service
